<template>
  <div class="module-card">
    <div class="module-header">
      <h3>成员管理</h3>
      <button @click="showAddMemberDialog = true" class="btn-primary">添加成员</button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-group">
        <input 
          v-model="searchForm.keyword"
          placeholder="请输入姓名或学号"
          class="search-input"
          @keyup.enter="handleSearch"
          style="padding: 12px 16px; font-size: 16px; min-width: 300px;"
        >
        <button @click="handleSearch" class="btn-search" style="padding: 12px 24px; font-size: 16px;">搜索</button>
        <button @click="resetSearch" class="btn-reset" style="padding: 12px 24px; font-size: 16px;">重置</button>
      </div>
    </div>

    <div style="overflow-x: auto;">
    <table class="data-table" style="width: 100%; min-width: 900px;">
      <thead>
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>学号</th>
          <th>部门</th>
          <th>职位</th>
          <th>入社时间</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(member, index) in displayedMembers" :key="member.id">
          <td>{{ (currentPage - 1) * pageSize + index + 1 }}</td>
          <td>{{ member.username }}</td>
          <td>{{ member.studentId }}</td>
          <td>{{ getDepartmentName(member.departmentId) }}</td>
          <td>{{ member.position }}</td>
          <td>{{ formatJoinTime(member.joinTime) }}</td>
          <td>{{ member.status === 'active' ? '正常' : '禁用' }}</td>
          <td class="operation-buttons">
            <button @click="handleChangeStatus(member)" class="btn-status">
              {{ member.status === 'active' ? '禁用' : '启用' }}
            </button>
            <button @click="handleDeleteMember(member.id)" class="btn-delete">删除</button>
            <button @click="navigateToDetail(member.id)" class="btn-view">详情</button>
          </td>
        </tr>
        <tr v-if="zhuchiMembers.length === 0">
          <td colspan="8" class="no-data">暂无成员数据</td>
        </tr>
      </tbody>
    </table>
    </div>
    <!-- 分页组件 -->
    <div class="pagination-container" v-if="totalPages > 1">
      <div class="pagination-info">
        共 {{ totalMembers }} 条记录，第 {{ currentPage }} / {{ totalPages }} 页
      </div>
      <div class="pagination">
        <button 
          @click="goToPage(1)"
          :disabled="currentPage === 1"
          class="pagination-btn"
        >
          首页
        </button>
        <button 
          @click="goToPage(currentPage - 1)"
          :disabled="currentPage === 1"
          class="pagination-btn"
        >
          上一页
        </button>
        <button 
          v-for="page in pageNumbers"
          :key="page"
          @click="goToPage(page)"
          :class="['pagination-btn', { active: currentPage === page }]"
        >
          {{ page }}
        </button>
        <button 
          @click="goToPage(currentPage + 1)"
          :disabled="currentPage === totalPages"
          class="pagination-btn"
        >
          下一页
        </button>
        <button 
          @click="goToPage(totalPages)"
          :disabled="currentPage === totalPages"
          class="pagination-btn"
        >
          末页
        </button>
      </div>
    </div>
    <!-- 添加成员弹窗 -->
    <div v-if="showAddMemberDialog" class="dialog-overlay">
      <div class="dialog">
        <div class="dialog-header">
          <h3>添加成员</h3>
          <button @click="closeMemberDialog" class="dialog-close">&times;</button>
        </div>
        <div class="dialog-content">
          <div class="form-group">
            <label>姓名：</label>
            <input v-model="memberForm.username" required>
          </div>
          <div class="form-group">
            <label>学院：</label>
            <input v-model="memberForm.college" required>
          </div>
          <div class="form-group">
            <label>学号：</label>
            <input v-model="memberForm.studentId" required>
          </div>
          <div class="form-group">
            <label>联系电话：</label>
            <input v-model="memberForm.phone" required>
          </div>
          <div class="form-group">
            <label>部门：</label>
            <select v-model="memberForm.departmentId" required>
              <option v-for="(name, id) in departmentMap" :key="id" :value="id">{{ name }}</option>
            </select>
          </div>
          <div class="form-group">
            <label>职位：</label>
            <select v-model="memberForm.position" required>
              <option value="部长">部长</option>
              <option value="副部长">副部长</option>
              <option value="部员">部员</option>
            </select>
          </div>
          <div class="form-group">
            <label>入社年份：</label>
            <input v-model="memberForm.joinTime" type="number" min="2000" max="2099" required>
          </div>
          <div class="form-group">
            <label>备注：</label>
            <textarea v-model="memberForm.note" rows="3"></textarea>
          </div>
        </div>
        <div class="dialog-footer">
          <button @click="saveMember" class="btn-primary">添加</button>
          <button @click="closeMemberDialog" class="btn-secondary">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const zhuchiMembers = ref([])
const showAddMemberDialog = ref(false)
const editingMember = ref(null)

// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(5)
const totalMembers = ref(0)

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

const memberForm = reactive({
  username: '',
  college: '',
  studentId: '',
  phone: '',
  departmentId: 3, // 主持队部门ID
  position: '部员',
  joinTime: new Date().getFullYear(),
  status: 'active',
  note: ''
})

// 部门映射表
const departmentMap = {
  1: '采播部',
  2: '电台部',
  3: '主持部',
  4: '新媒体部',
  5: '技术部',
  6: '办公室',
  7: '运营部',
  8: '摄影部',
  9: '网宣部'
}
// 计算属性：当前页显示的成员
const displayedMembers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return zhuchiMembers.value.slice(start, end)
})

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(totalMembers.value / pageSize.value)
})

// 计算显示的页码
const pageNumbers = computed(() => {
  const pages = []
  const maxVisiblePages = 5
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2))
  let endPage = startPage + maxVisiblePages - 1
  
  if (endPage > totalPages.value) {
    endPage = totalPages.value
    startPage = Math.max(1, endPage - maxVisiblePages + 1)
  }
  
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }
  
  return pages
})
// 获取部门名称
const getDepartmentName = (deptId) => {
  return departmentMap[deptId] || '未知部门'
}

// 格式化入社时间
const formatJoinTime = (time) => {
  if (!time) return '未填写'
  if (typeof time === 'string' && time.includes('-')) {
    return time.split('T')[0] // 处理日期字符串
  }
  return time
}

// 获取成员列表
const fetchMembers = async () => {
  try {
    const response = await fetch('http://localhost:8080/user/department/3', {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    })
    const result = await response.json()
    
    if (result.code === 200) {
      zhuchiMembers.value = result.data.map(member => ({
        ...member,
        joinTime: member.join_time || member.joinTime // 兼容不同字段名
      }))
      // 关键：更新总成员数
      totalMembers.value = zhuchiMembers.value.length
    } else {
      throw new Error(result.message || '获取成员列表失败')
    }
  } catch (error) {
    console.error('获取成员列表失败:', error)
    alert('获取成员列表失败，请稍后重试')
  }
}
// 搜索功能
const handleSearch = () => {
  if (!searchForm.keyword.trim()) {
    // 如果搜索关键词为空，显示所有成员
    fetchMembers()// 重置时会通过fetchMembers更新totalMembers
    return
  }
  
  // 过滤成员数据
  const filteredMembers = zhuchiMembers.value.filter(member => 
    member.username.includes(searchForm.keyword.trim()) || 
    member.studentId.includes(searchForm.keyword.trim())
  )
  
  zhuchiMembers.value = filteredMembers
  totalMembers.value = filteredMembers.length
  currentPage.value = 1 // 重置到第一页
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  fetchMembers()
}

// 分页功能
const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

// 关闭成员对话框
const closeMemberDialog = () => {
  showAddMemberDialog.value = false
  // 重置表单
  Object.keys(memberForm).forEach(key => {
    if (key === 'departmentId') {
      memberForm[key] = 3 // 重置为主持队
    } else if (key === 'position') {
      memberForm[key] = '部员'
    } else if (key === 'joinTime') {
      memberForm[key] = new Date().getFullYear()
    } else if (key === 'status') {
      memberForm[key] = 'active'
    } else {
      memberForm[key] = ''
    }
  })
  editingMember.value = null
}

// 保存成员
const saveMember = async () => {
  try {
    // 表单验证
    if (!memberForm.username || !memberForm.studentId || !memberForm.phone) {
      alert('请填写必填字段')
      return
    }

    const url = editingMember.value ? 
      `http://localhost:8080/user/${editingMember.value.id}` : 
      'http://localhost:8080/user'
    const method = editingMember.value ? 'PUT' : 'POST'

    const response = await fetch(url, {
      method: method,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        ...memberForm,
        join_time: memberForm.joinTime // 确保字段名正确
      })
    })

    const result = await response.json()

    if (result.code === 200) {
      alert(editingMember.value ? '成员更新成功' : '成员添加成功')
      closeMemberDialog()
      fetchMembers() // 重新获取成员列表
    } else {
      throw new Error(result.message || (editingMember.value ? '更新成员失败' : '添加成员失败'))
    }
  } catch (error) {
    console.error(editingMember.value ? '更新成员失败:' : '添加成员失败:', error)
    alert(error.message)
  }
}

// 修改成员状态
const handleChangeStatus = async (member) => {
  try {
    const newStatus = member.status === 'active' ? 'inactive' : 'active'
    const response = await fetch(`http://localhost:8080/user/${member.id}/status`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({ status: newStatus })
    })

    const result = await response.json()

    if (result.code === 200) {
      alert(`成员${newStatus === 'active' ? '启用' : '禁用'}成功`)
      fetchMembers() // 重新获取成员列表
    } else {
      throw new Error(result.message || '修改成员状态失败')
    }
  } catch (error) {
    console.error('修改成员状态失败:', error)
    alert(error.message)
  }
}

// 删除成员
const handleDeleteMember = async (id) => {
  if (!confirm('确定要删除该成员吗？')) {
    return
  }

  try {
    const response = await fetch(`http://localhost:8080/user/${id}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    })

    const result = await response.json()

    if (result.code === 200) {
      alert('成员删除成功')
      fetchMembers() // 重新获取成员列表
    } else {
      throw new Error(result.message || '删除成员失败')
    }
  } catch (error) {
    console.error('删除成员失败:', error)
    alert(error.message)
  }
}

// 跳转到详情页
const navigateToDetail = (id) => {
  router.push(`/buzhang/zhuchi/memberDetail/${id}`)
}

// 页面加载时获取成员列表
onMounted(() => {
  fetchMembers()
})
</script>

<style scoped>
.module-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.module-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-primary:hover {
  background-color: #66b1ff;
}

.search-section {
  margin-bottom: 20px;
}

.search-group {
  display: flex;
  gap: 10px;
}

.search-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none;
}

.search-input:focus {
  border-color: #409eff;
}

.btn-search, .btn-reset {
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-search {
  background-color: #f5f7fa;
}

.btn-search:hover, .btn-reset:hover {
  background-color: #f0f0f0;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  text-align: left;
}

.data-table th, .data-table td {
  padding: 12px 15px;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

.operation-buttons {
  display: flex;
  gap: 8px;
}

.btn-status, .btn-delete, .btn-view {
  padding: 4px 10px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-status {
  background-color: #e6a23c;
  color: white;
}

.btn-status:hover {
  background-color: #f39c12;
}

.btn-delete {
  background-color: #f56c6c;
  color: white;
}

.btn-delete:hover {
  background-color: #e74c3c;
}

.btn-view {
  background-color: #409eff;
  color: white;
}

.btn-view:hover {
  background-color: #66b1ff;
}

.no-data {
  text-align: center;
  color: #909399;
  padding: 20px 0;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.pagination-info {
  color: #909399;
}

.pagination {
  display: flex;
  gap: 5px;
}

.pagination-btn {
  padding: 5px 10px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.pagination-btn:hover:not(.active):not(:disabled) {
  background-color: #f5f7fa;
}

.pagination-btn.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination-btn:disabled {
  cursor: not-allowed;
  color: #c0c4cc;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog {
  background-color: #fff;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.dialog-close {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #909399;
}

.dialog-content {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group input, .form-group select, .form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none;
}

.form-group input:focus, .form-group select:focus, .form-group textarea:focus {
  border-color: #409eff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  border-top: 1px solid #eee;
}

.btn-secondary {
  background-color: #f5f7fa;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-secondary:hover {
  background-color: #e4e7ed;
}

@media (max-width: 768px) {
  .module-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .search-group {
    flex-direction: column;
  }

  .operation-buttons {
    flex-direction: column;
  }

  .pagination-container {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }

  .pagination {
    flex-wrap: wrap;
  }
}
</style>